import bluetooth from './bluetooth';
import { CHARID, SERIVCEID } from './const';
import { dataConversion, formatNumByLen, handleStringBuffer, hexStr2Num } from './number';

let Table_CRC8 = [
    0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
    0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
    0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
    0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
    0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
    0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
    0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
    0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
    0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
    0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
    0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
    0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
    0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
    0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
    0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
    0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
];

function formatFileName(fileName) {
    let fileNameSize = fileName.length.toString(16)
    fileNameSize = fileNameSize.length < 4 ? '0'.repeat(4 - fileNameSize.length) + fileNameSize : fileNameSize
    return dataConversion(fileNameSize)
}
export function crc8(buf) {
    if (buf == null || buf.length == 0) {
        return 0;
    }
  
    let crc = 0;
  
    for (let i = 0; i < buf.length - 1; i++) {
        crc = Table_CRC8[0x00ff & (crc ^ (parseInt('0x' + buf[i], 16)))]
    }

    return crc.toString(16);
}
function convertToHex(decimal) {
  let hexadecimal = decimal.toString(16).padStart(2, "0");
  return hexadecimal;
}
function getReadFileCmd(packageNum = 0) {
    const arr = ['AA', '04', 'FB', convertToHex(packageNum), '00', '00', '00', null]

    arr[arr.length - 1] = crc8(arr)
    return handleStringBuffer(arr)
}

function getEndReadCmd() {
    const cmd = 'aa 05 fa 00 00 00 00 21'
    let arr = cmd.split(' ')
    arr.push(null)
    arr[arr.length - 1] = crc8(arr)
    return handleStringBuffer(arr)
}

export function startReadPkgCmd(fileName) {
    fileName = fileName + '\0'
    const fileNameSize = formatFileName(fileName)

    const stringBuffer = ['AA', '03', 'FC', '00', '00', fileNameSize.slice(0, 2), fileNameSize.slice(2)]

    // console.log(fileName, stringBuffer)
    fileName.split('').forEach((item, index) => {
        stringBuffer[index + 7] = item.charCodeAt().toString(16)
    })
    // console.log(stringBuffer)

    stringBuffer.push(null)
    stringBuffer[stringBuffer.length - 1] = crc8(stringBuffer)
    return handleStringBuffer(stringBuffer)
}

export const startReadPkg = ({
    deviceId,
    fileName
}) => {
    const cmd = startReadPkgCmd(fileName)
		console.log(cmd, '发送命令读取文件名-------')
    const buffer = cmd
    return new Promise((resolve, reject) => {
        var length = buffer.length;
        // 假设每个分片的长度为 chunkSize
        var chunkSize = 20;
        // 计算需要分成多少个分片
        var numChunks = Math.floor(length / chunkSize) + (length % chunkSize > 0 ? 1 : 0);
        // 连接成功后，发起数据分片写入
    for (var i = 0; i < numChunks; i++) {
        // 计算当前分片的起始和结束索引
        var start = i * chunkSize;
        var end = start + chunkSize;
  
        // 获取当前分片的数据
        var chunk = buffer.substring(start, end);
        console.log(bluetooth.hexStr2Buffer(chunk));
        // 将当前分片的数据写入蓝牙设备
        wx.writeBLECharacteristicValue({
            deviceId,
            serviceId: SERIVCEID,
            characteristicId: CHARID.WRITE,
            value: bluetooth.hexStr2Buffer(chunk),
          success: function(res) {
            // 写入成功，继续下一个分片的写入
            console.log("写入分片数据成功");
            resolve({
                deviceId,
                serviceId: SERIVCEID,
                characteristicId: CHARID.NOTIFY
            })
          },
          fail: function(res) {
            // 写入失败，处理错误
            console.log(err, 'send failed')
            reject()
          }
        });
      }
        // wx.writeBLECharacteristicValue({
        //     deviceId,
        //     serviceId: SERIVCEID,
        //     characteristicId: CHARID.WRITE,
        //     value: buffer,
        //     success(res) {
        //         setTimeout(() => {
        //             resolve({
        //                 deviceId,
        //                 serviceId: SERIVCEID,
        //                 characteristicId: CHARID.NOTIFY
        //             })
        //         }, 2000)
        //     },
        //     fail() {
        //         reject()
        //     }
        // })
    })
}

export const stopReadPkg = ({
    deviceId
}) => {
    const cmd = getEndReadCmd()
    const buffer = bluetooth.hexStr2Buffer(cmd)

    return new Promise((resolve, reject) => {
        wx.writeBLECharacteristicValue({
            deviceId,
            serviceId: SERIVCEID,
            characteristicId: CHARID.WRITE,
            value: buffer,
            success(res) {
                setTimeout(() => {
                    resolve({
                        deviceId
                    })
                }, 2000)
            },
            fail() {
                reject()
            }
        })
    })
}

export const readFileData = ({
    deviceId,
    packageNum
}) => {
    const cmd = getReadFileCmd(packageNum)
    console.log(cmd, 'cmd发送的包指令-----4444-------')
    const buffer = bluetooth.hexStr2Buffer(cmd)
    return new Promise((resolve, reject) => {
//-------------
        wx.writeBLECharacteristicValue({
            deviceId,
            serviceId: SERIVCEID,
            characteristicId: CHARID.WRITE,
            value: buffer,
            success(res) {
                resolve({
                    deviceId,
                    serviceId: SERIVCEID,
                    characteristicId: CHARID.NOTIFY
                })
            },
            fail(err) {
                console.log(err, 'send failed')
                reject()
            }
        })
    })
}

const formatFileNameByDate = ({
    year,
    month,
    day,
    hour,
    minute,
    second
}) => {
    month = formatNumByLen(month, 2)
    day = formatNumByLen(day, 2)
    hour = formatNumByLen(hour, 2)
    minute = formatNumByLen(minute, 2)
    second = formatNumByLen(second, 2)
    return `${year}${month}${day}${hour}${minute}${second}`
}

export const formatEcgData = (data) => {
    const diff = 10
    const len = data.length / diff
    const isRight = data.length % diff === 0
    if(!isRight) {
        console.error("this is a error data")
        return ''
    }
    const arr = []
    for(let i = 0; i <= len -1; i ++) {
        const item = data.slice(i * diff, i*diff + diff)
        const year = hexStr2Num(dataConversion(item.slice(0, 2).join('')))
        const month = hexStr2Num(item.slice(2, 3).join(''))
        const day = hexStr2Num(item.slice(3, 4).join(''))
        const hour = hexStr2Num(item.slice(4, 5).join(''))
        const minute = hexStr2Num(item.slice(5, 6).join(''))
        const second = hexStr2Num(item.slice(6, 7).join(''))
        const measureType = hexStr2Num(item.slice(7, 8).join('')) // Measure type(0:inside, 1:outside）
        const faceType = hexStr2Num(item.slice(11).join('')) // smile face or crying face (0: smile face,1: crying face, other value: Do not display)
        const isContainSpeech = hexStr2Num(item.slice(9).join('')) // Contains speech or not(0:NO，1:YES) 

        arr.push({
            year,
            month,
            day,
            hour,
            minute,
            second,
            measureType,
            faceType,
            isContainSpeech,
            fileName: formatFileNameByDate({
                year,
                month,
                day,
                hour,
                minute,
                second
            })
        })
    }

    return arr
}

export const formatTmpData = (data) => {
    // console.log(data, 'tmp')

    const len = data.length / 11
    const isRight = data.length % 11 === 0

    if(!isRight) {
        console.error("this is a error data")
        return ''
    }
    const arr = []

    for(let i = 0; i <= len -1; i ++) {
        const item = data.slice(i * 11, i*11 + 11)
        const year = hexStr2Num(dataConversion(item.slice(0, 2).join('')))
        const month = hexStr2Num(item.slice(2, 3).join(''))
        const day = hexStr2Num(item.slice(3, 4).join(''))
        const hour = hexStr2Num(item.slice(4, 5).join(''))
        const minute = hexStr2Num(item.slice(5, 6).join(''))
        const second = hexStr2Num(item.slice(6, 7).join(''))
        const measureType = hexStr2Num(item.slice(7, 8).join('')) // Measure type(0:inside, 1:outside）
        const tempVal = hexStr2Num(dataConversion(item.slice(8, 10).join(''))) // Temperature value(e.g. the value 385 represents 38.5℃)
        const faceType = hexStr2Num(item.slice(10).join('')) // smile face or crying face (0: smile face,1: crying face, other value: Do not display)
        
        arr.push({
            year,
            month,
            day,
            hour,
            minute,
            second,
            measureType,
            tempVal,
            faceType
        })
    }

    console.log(arr)
    return arr
}

export const formatOxiData = (data) => {
    const diff = 12

    const len = data.length / diff
    const isRight = data.length % diff === 0

    if(!isRight) {
        console.error("this is a error data")
        return ''
    }

    const arr = []

    for(let i = 0; i <= len -1; i ++) {
        const item = data.slice(i * diff, i*diff + diff)
        const year = hexStr2Num(dataConversion(item.slice(0, 2).join('')))
        const month = hexStr2Num(item.slice(2, 3).join(''))
        const day = hexStr2Num(item.slice(3, 4).join(''))
        const hour = hexStr2Num(item.slice(4, 5).join(''))
        const minute = hexStr2Num(item.slice(5, 6).join(''))
        const second = hexStr2Num(item.slice(6, 7).join(''))
        const measureType = hexStr2Num(item.slice(7, 8).join('')) // Measure type(0:inside, 1:outside）
        const sop2Val = hexStr2Num(item.slice(8, 9).join('')) // SPO2 value (e.g. the value 99 represents 99%)
        const pr = hexStr2Num(item.slice(9, 10).join('')) // PR（0-255）
        const pi = hexStr2Num(item.slice(10, 11).join('')) // PI(e.g. the value 55 represents 5.5%)
        const faceType = hexStr2Num(item.slice(11).join('')) // smile face or crying face (0: smile face,1: crying face, other value: Do not display)

        arr.push({
            year,
            month,
            day,
            hour,
            minute,
            second,
            measureType,
            sop2Val,
            pr,
            pi,
            faceType
        })
    }

    console.log(arr)
    return arr
}

export const parseResponse = (data) => {
    const bufferSizeStr = data.slice(5, 7).join('')
    const len = hexStr2Num(dataConversion(bufferSizeStr))

    const contentStr = dataConversion(data.slice(7, len + 7).join(''))

    // console.log(header, isAckOk, bufferSizeStr, bufferSize, data.length)
    return {
        len,
        contentStr,
        content: data.slice(7, len + 7)
    }
}

function getEcgItemResult(type) {
    let result = ''
    let explain = ''

    if (type == 0) {
        result = "结果：常规心电节律"
        explain = "解读：窦性心律,凡起源于窦房结的心律，称为窦性心律。窦性心律属于正常节律。临床意义:窦房结是心脏搏动的最高司令部，正常的心脏必须有正常的窦房结，正常的窦房结具有强大的自律性。窦房结自律性除受自主神经调节外，还受温度、血氧饱和度和其他代谢过程的影响。心脏的正常跳动就应该是窦性心律。窦性心律的个体差异性受很多因素影响，包括年龄、性别和自主神经调节。6岁之后，随着年龄的增长，心律会逐渐减慢，青少年和成年人安静时心率大约65~85次/分，到老年心率更趋缓慢。体温升高加速窦性心率，体温每升高1度，窦性心律增快8次/分。血氧饱和度的增加可减慢窦性心率，血氧饱和度的降低则使窦性心律增加。建议：窦性心律为正常心脏节律，无需特殊检查；如果有症状，仍需要进一步检查。"
    } else if (type == 1) {
        result = "结果：高心率"
        explain = "解读：窦性心动过速,成人窦性心律的频率超过100次/分，称为窦性心动过速。临床意义:窦性心动过速是人体生理性或病理性应激反应的表现，通常是由于迷走神经张力减弱，或交感神经张力增高的结果。1.生理性因素：包括运动、恐惧、情绪激动；2.生活习惯：饮用茶、咖啡、酒精等刺激性饮品，吸烟（尼古丁刺激）等；3.病理状态：包括发热、低血压、心肌缺血、心力衰竭、贫血或出血、低氧血症、甲状腺功能亢进、休克。4.药物因素：拟交感胺或其他肾上腺素能激动剂、阿托品和其他抗胆碱能药物。建议：窦性心动过速通常不是原发性心律失常，应采取如下措施：精神放松，避免体力活动；禁吸烟、饮酒、咖啡及茶；去除药物因素影响，监测心率，复查心电图。经上述处理仍有窦性心动过速，建议到医院就诊，明确引起窦性心动过速的原因，必要时进一步治疗。"
    } else if (type == 2) {
        result = "结果：低心率"
        explain = "解读：窦性心动过缓,窦性心律慢于每分钟60次称为窦性心动过缓；常伴有心律不齐，严重窦性心动过缓可产生逸搏。窦性P波的频率通常为45~59次/分，偶尔可慢至40次/分。临床意义:多见于正常人，反映其心血管状态良好，正常成人睡眠时心率可慢至30~40次/分，训练有素的运动员或强壮的体力劳动者安静时心率可在50次/分左右。其他常见原因包括：1.心脏相关药物影响：β受体阻滞剂、钙通道阻滞剂（硫氮䓬酮、维拉帕米）、胺碘酮、洋地黄、伊伐布雷定等。2.相关疾病：包括病态窦房结综合征、中枢神经影响、革兰阴性杆菌败血症、颈部肿瘤、纵膈肿瘤、阻塞性黄疸、低体温、心肌梗死（尤其急性下壁心肌梗死）、粘液性水肿。3.迷走神经张力过度增高：可产生明显窦性心动过缓，可能属于病理性。4.窦房结功能障碍：常表现为难以解释的严重窦性心动过缓，可能是心脏停搏的先兆。5.呕吐反射。6.其他药物：中枢性镇静剂、西咪替丁等。建议：1.无症状的窦性心动过缓通常不需要治疗。2.如有头晕、胸闷、甚至晕厥等症状，建议咨询医生寻找原发疾病，必要时应考虑植入永久性心脏起搏器。3.如果是冠心病、心绞痛、心肌梗死、心衰患者，通常需要服用药物，将心率控制在55~60次/分（安静状态下处于窦性心动过缓状态）。如果心率控制不达标，也需要到门诊就医，实现心率达标。"
    } else if (type == 4) {
        result = "结果：高QRS值"
        explain = "解读：室内阻滞,可分为束支传导阻滞和分支传导阻滞；心电图QRS波群时限大于0.12s。既不像左束支阻滞图像也不像右束支阻滞图像时，又称为非特异性室内传导阻滞。临床意义:室内阻滞多属于心脏传导组织器质性损伤，但临床预后判断还应结合心脏基础病变的性质及其他有关资料判定。常见病因包括冠心病、心肌梗死、心肌炎、扩张型心肌病、克山病、风心病、电解质紊乱等。阻滞部位在束支的远端浦肯野纤维系统或心室肌细胞与浦肯野纤维的交界处，这类患者常合并多源性特宽型室性早搏。新发生的完全性左束支阻滞，需考虑急性心肌梗死。室内阻滞合并心力衰竭者预后不良。建议：主要针对病因，若左、右束支同时阻滞，则将引起完全性房室传导阻滞，这时因为心室起搏点位置低，其频率较慢，易致心源性晕厥发作，应考虑及早安装人工心脏起搏器。建议到医院就诊，明确引起的原因，必要时进一步治疗。"
    } else if (type == 8) {
        result = "结果：高ST值"
        explain = "解读：ST段抬高的原因有很多，植物神经功能紊乱、心包炎、病毒性心肌炎、变异性心绞痛、早期复极综合征等多种原因都可以导致心电图异常表现，其中最严重的是急性心肌梗死。ST段抬高是指心电图ST段在等电位线以上，还需要注意ST段抬高的程度、形态、持续时间以及患者的症状。胸痛伴有ST段急剧的抬高，为冠状动脉阻塞或其他原因导致的心肌损害，患者这时往往有持续、严重的胸痛，心肌缺血的其他临床表现和体征，以及实验室化验的改变，其中最敏感的是肌钙蛋白的升高。因此做心电图检查时一旦发现ST段抬高，应该做心肌标志物等化验、心脏彩超来进一步明确，必要时可以做冠状动脉造影检查来明确诊断，早发现、早治疗。治疗包括药物治疗、手术治疗，以及改善生活方式。药物治疗包括控制血压、抗动脉粥样硬化、抗血小板聚集、缓解心绞痛等，手术治疗包括支架的治疗、外科冠脉搭桥以及改善生活方式。建议到医院就诊，明确引起的原因，必要时进一步治疗。"
    } else if (type == 16) {
        result = "结果：低ST值"
        explain = "解读：ST段压低提示存在心肌细胞的损伤，最常见的原因是心肌的缺血，比如心绞痛、心肌梗死的患者，因为血管的狭窄导致心肌细胞的缺血，就会出现ST段的压低。有一部分心肌肥厚的患者如果出现了心肌的劳损，也会出现ST段的压低以及T波倒置。因此心电图出现ST段的压低，需要结合症状、病史等，除外有无心肌缺血存在的可能性，必要的情况下应该完善心脏彩超，心脏的冠状动脉CTA等检查，甚至可以住院进行冠状动脉造影检查，明确有无冠状动脉血管的狭窄，以及有无植入心脏支架的适应症，从而改善心肌缺血。建议到医院就诊，明确引起的原因，必要时进一步治疗。"
    } else if (type == 32) {
        result = "结果：心电图节律不规则"
        explain = "解读：RR间期是指心电图上两个R波之间的时限。正常的RR间期时限应该在0.6-1.0秒之间，小于0.6秒说明出现了心动过速，大于1.0秒说明出现了心动过缓。另外当RR间期不相等的时候，说明出现了心律不齐，如房颤，房室传导阻滞，建议到医院就诊，明确引起的原因，必要时进一步治疗。"
    } else if (type == 64) {
        result = "结果：疑似早搏"
        explain = "解读：过早搏动可发生于正常人。但心脏神经官能症与器质性心脏病患者更易发生。情绪激动，神经紧张，疲劳，消化不良，过度吸烟、饮酒或喝浓茶等均可引起发作，亦可无明显诱因，洋地黄、钡剂、奎尼丁、拟交感神经类药物、氯仿、环丙烷麻醉药等毒性作用，缺钾以及心脏手术或心导管检查都可引起。冠心病、晚期二尖瓣病变、心脏病、心肌炎、甲状腺功能亢进性心脏病、二尖瓣脱垂等常易发生过早搏动。建议到医院就诊，明确引起的原因，必要时进一步治疗。"
    } else if (type == 255) {
        result = "结果：波形质量差，或者导联一直脱落等算法无法分析的情况。"
        explain = "解读：数据质量差，建议请重新戴机测试。"
    }

    return {
        result,
        explain
    }
}

function formatTime(current) {
    const month = formatNumByLen(current.getMonth(), 2)
    const date = formatNumByLen(current.getDate(), 2)
    const hour = formatNumByLen(current.getHours(), 2)
    const minute = formatNumByLen(current.getMinutes(), 2)
    const second = formatNumByLen(current.getSeconds(), 2)
    return `${current.getFullYear()}${month}${date}${hour}${minute}${second}`
}

export function getEcgWaveChart(waveList, fileName, diff = 100) {
    // waveList 一秒钟500个点 根据文件名截取
    // fileName 是数据存储时间 yyyymmddhhmmss
    const year = fileName.slice(0, 4)
    const month = fileName.slice(4, 6)
    const date = fileName.slice(6, 8)
    const hour = fileName.slice(8, 10)
    const minute = fileName.slice(10, 12)
    const second = fileName.slice(12)

    const startTime = new Date(year, month -1, date, hour, minute, second)
    
    // 绘制时不绘制全部 数量量多大 取100ms 一个点 间隔可后续自行调整

    const xAxisData = [fileName]
    const yAxisData = [waveList[0]]

    for(let i = diff; i < waveList.length; i += diff) {
        const yAxisItem = waveList[i]
        
        if(yAxisItem) {
            const current = new Date(startTime.getTime() + i)
            const xAxisItem = formatTime(current)
            xAxisData.push(xAxisItem)
            yAxisData.push(yAxisItem)
        } else {
            continue
        }
    }

    return {
        xAxisData,
        yAxisData
    }
}

function getNum (hex) {
    let binary = "";
  
    // 将十六进制转换为二进制
    for (let i = 0; i < hex.length; i++) {
      let digit = parseInt(hex.charAt(i), 16).toString(2).padStart(4, '0');
      binary += digit;
    }
    return binary
  }
 function myAtoi (v) {
    let binary = getNum(v); // 输入二进制数
    let decimal;
    // 判断最高位是否为1，确定符号
    if (binary.charAt(0) === '1') {
        // 取反
        let complement = "";
        for (let i = 0; i < binary.length; i++) {
        complement += (binary.charAt(i) === '0') ? '1' : '0';
        }
        
        // 加1
        let incremented = "";
        let carry = 1;
        for (let i = complement.length - 1; i >= 0; i--) {
        let sum = parseInt(complement.charAt(i)) + carry;
        incremented = (sum % 2) + incremented;
        carry = Math.floor(sum / 2);
        }
        
        // 转换为十进制并加上负号
        decimal = -parseInt(incremented, 2);
    } else {
        // 最高位为0，直接转换为十进制
        decimal = parseInt(binary, 2);
    }
    return decimal
}

export const parseEcgFileData = (data) => {
    console.log(data);
    const hrSize = hexStr2Num(dataConversion(data.slice(0, 2).join('')))
    const waveSize = hexStr2Num(dataConversion(data.slice(2, 6).join('')))
    const mainLen = 21

    // console.log(data, mainLen, hrSize, waveSize)
    // if(data.length <= mainLen + hrSize + waveSize) {
    //     console.error('error data')
    //     return false
    // }

    const hr = hexStr2Num(dataConversion(data.slice(6, 8).join(''))) // Diagnostic results: HR, unit: bpm
    const st = hexStr2Num(dataConversion(data.slice(8, 10).join(''))) // Diagnostic results: ST, unit: mV e.g. the vale 0x0004 represents the ST is 0.04mV
    const qrs = hexStr2Num(dataConversion(data.slice(10, 12).join(''))) // Diagnostic results: QRS, unit: ms
    const pvcs = hexStr2Num(dataConversion(data.slice(12, 14).join(''))) // Diagnostic results: The number of PVCs
    const qtc = hexStr2Num(dataConversion(data.slice(14, 16).join(''))) // Diagnostic results: QTc, unit: ms
    const type = hexStr2Num(dataConversion(data.slice(16, 17).join(''))) // Diagnostic results: Arrhythmia refer to the table below 
    const measureType = hexStr2Num(dataConversion(data.slice(17, 18).join(''))) // Measure type
    const filterMode = hexStr2Num(dataConversion(data.slice(18, 19).join(''))) // Filtering mode(0: normal, 1: wide) 
    const qt = hexStr2Num(dataConversion(data.slice(19, 21).join(''))) // QT(ms) 


    let dataPos = 19 + hrSize;//19 is the head length; timeLength*2 is HR data length
    const waveList = []
    function addDataSample(data, num) {
        waveList[num] = data;
    }
    for (let i = dataPos; (i-dataPos) < waveSize - 2; i += 2){
			let tempData1 = myAtoi(dataConversion(data.slice(i, i + 2).join('')))
			let tempData2 = myAtoi(dataConversion(data.slice(i + 2, i + 4).join(''))) 
			let tempData3 = (tempData1 + tempData2) / 2 
			addDataSample(tempData3, i - dataPos)
			addDataSample(tempData2, i - dataPos + 1)
    }
    const summary = getEcgItemResult(type)

    return {
        hr,
        st,
        qrs,
        pvcs,
        qtc,
        type,
        measureType,
        filterMode,
        qt,
        waveList,
        summary
    }
}

